// Copyright (c) 2022 Presto Labs Pte. Ltd.
// Author: fengyang

#pragma once

#include <boost/algorithm/string.hpp>
#include <map>
#include <nlohmann/json.hpp>
#include <string>
#include <vector>

namespace coin2::exchange::crypto_common::feed_v2 {

using coin2::exchange::feed::WebsocketConfig;

class CryptoRequestGenerator : public base::feed::RequestGenerator {
 public:
  explicit CryptoRequestGenerator(const WebsocketConfig* ws_config)
      : config_(ws_config) {}
  virtual ~CryptoRequestGenerator() = default;

  virtual std::vector<std::string> GenerateRequests(
      const std::vector<std::string>& channels,
      const std::vector<std::string>& symbols,
      const std::map<std::string, std::string>& channel_templates,
      const std::string& request_template) {
    std::vector<std::string> reqs;
    std::vector<std::string> ch = channels;

    // kline
    std::vector<std::string> ch_kline;
    auto iter = ch.begin();
    while (iter != ch.end()) {
      if (StringStartsWith(*iter, "kline_rest")) {
        ch_kline.push_back(*iter);
        iter = ch.erase(iter);
      } else {
        iter++;
      }
    }

    if (!ch_kline.empty()) {
      auto timestamp = MarketTimestampProvider::GetTimestamp();
      boost::posix_time::ptime round_time = TimestampRoundHour(timestamp);
      for (auto& ch_k : ch_kline) {
        std::string c = channel_templates.at(ch_k);
        auto interval_time = GetInterval(c);
        for (auto& symbol : symbols) {
          std::vector<std::pair<int64_t, int64_t>> durations;
          bool long_query = base::feed::RequestGenerator::CheckLongQuery(
              round_time, symbol, ch_k, &last_long_query_time_);
          if (long_query) {
            durations = base::feed::RequestGenerator::GetDurations(
                config_->kline_length(), config_->kline_start(), config_->kline_end(),
                interval_time, 300);
          } else {
            // query small data
            durations = base::feed::RequestGenerator::GetDurations(
                "3", "", "",interval_time, 300);
          }

          for (const auto& d : durations) {
            std::string c_copy = c;
            // rest api symbol is upper
            boost::replace_all(c_copy, "{}", symbol);
            boost::replace_all(c_copy, "{count}", std::to_string((d.second - d.first) / interval_time));
            boost::replace_all(c_copy, "{end}", std::to_string(d.second / 1'000'000L));
            reqs.emplace_back(c_copy);
          }
        }
      }
    }

    if (!ch.empty()) {
      std::vector<std::string> channels_reqs;
      std::set<std::string> underlying_symbols;
      for (const auto& channel_name : ch) {
        for (const auto& symbol : symbols) {
          std::string subscription_symbol = symbol;
          if (channel_name == "index_price") {
            std::vector<std::string> splitted;
            splitted = Split(symbol, "-");
            CHECK_EQ(splitted.size(), 2);
            if (underlying_symbols.count(splitted[0]) > 0) continue;

            underlying_symbols.insert(splitted[0]);
            subscription_symbol = splitted[0] + "-INDEX";
          } 
          std::string c = channel_templates.at(channel_name);
          boost::replace_all(c, "{}", subscription_symbol);
          channels_reqs.push_back(c);
        }
      }

      std::string ch_str = boost::algorithm::join(channels_reqs, ", ");
      std::string s = request_template;
      boost::replace_all(s, "{channel}", ch_str);
      boost::replace_all(s, "{id}", std::to_string(id_));
      id_++;
      auto timestamp = MarketTimestampProvider::GetTimestamp();
      std::string nonce = std::to_string(timestamp / 1'000'000LL);
      boost::replace_all(s, "{nonce}", nonce);
      reqs.push_back(s);
    }

    return reqs;
  }

 private:
  int64_t GetInterval(const std::string& channel) {
    if (channel.find("timeframe=1m") != std::string::npos) {
      return (int64_t)60 * 1'000'000'000;
    } else if (channel.find("timeframe=5m") != std::string::npos) {
      return (int64_t)300 * 1'000'000'000;
    } else if (channel.find("timeframe=15m") != std::string::npos) {
       return (int64_t)900 * 1'000'000'000;
    } else if (channel.find("timeframe=1h") != std::string::npos) {
      return (int64_t) 60 * 60 * 1'000'000'000;
    }  else if (channel.find("timeframe=1D") != std::string::npos) {
      return (int64_t)24 * 60 * 60 * 1'000'000'000;
    } else {
      THROW() << "Not support new channel: " << channel;
    }

    return std::numeric_limits<int64_t>::quiet_NaN();
  }

  int id_ = 1;
  const WebsocketConfig* config_;
};

}  // namespace coin2::exchange::crypto_common::feed_v2
